﻿using System;
using NUnit.Framework;
using System.Net;
using System.Net.Sockets;
using System.IO;

namespace InTheHand.Net.Tests.ObexRequest
{
    [TestFixture]
    public class ListenerMisc
    {
        //Incomplete test[Test]
        public void aaaa()
        {
            byte[] input = new byte[10];
            WebHeaderCollection headers = new WebHeaderCollection();
            headers.Add("LENGTH", 20.ToString());
            ObexListenerRequest lsnrReq = CreateObexListenerRequest(input, headers);
        }

        private static ObexListenerRequest CreateObexListenerRequest(byte[] input, WebHeaderCollection headers)
        {
            Type[] paramTypes = new Type[] {
                typeof(byte[]), typeof(WebHeaderCollection),
                typeof(EndPoint), typeof(EndPoint) };
            System.Reflection.ConstructorInfo ctorInfo
                = typeof(ObexListenerRequest).GetConstructor(
                    System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance,
                    null, paramTypes, null);
            Object[] args = new Object[] { input, headers,
                new IPEndPoint(1,1), new IPEndPoint(2,2) };
            ObexListenerRequest lsnrReq = (ObexListenerRequest)ctorInfo.Invoke(args);
            return lsnrReq;
        }

    }

    [TestFixture]
    public class UriFormats
    {
        ObexWebRequest CreateObexWebRequestOfClassThatThrows(Uri requestUri)
        {
            ObexWebRequest req = new ObexWebRequest(requestUri);
            return req;
        }

        ObexWebRequest CreateObexWebRequestOfClassThatDoesNotThrow(Uri requestUri)
        {
            ObexWebRequest req = new ObexWebRequest(requestUri);
            return req;
        }


        [Test]
        [ExpectedException(typeof(UriFormatException))]
        public void BadUriScheme()
        {
            Uri uri = new Uri("xxxxxxxxx://11223344/foo.txt");
            ObexWebRequest req = CreateObexWebRequestOfClassThatThrows(uri);
        }

        //Depends on non-existence of chosen arbitrary address, and could be slow, so don't run.
        //[Test]
        //public void BadUriIrdaNoSuchPeer()
        //{
        //    Uri uri = new Uri("obex://00000000/foo.txt");
        //    ObexWebRequest req = CreateObexWebRequestOfClassThatThrows(uri);
        //    req.GetResponse();
        //}

        [Test]
        public void BadUriBadHostFormat()
        {
            Uri uri = new Uri("obex://0000000000000000000000000/foo.txt");
            ObexWebRequest req = CreateObexWebRequestOfClassThatThrows(uri);
            try {
                req.GetResponse();
                Assert.Fail("Should have thrown!");
            } catch (WebException we) {
                Exception innerException = we.InnerException;
                Assert.IsNotNull(innerException);
                SocketException sex = innerException as SocketException;
                Assert.IsNotNull(sex);
                const int WSAEADDRNOTAVAIL = 10049; // (SocketError enum not in CF)
                int err = sex.ErrorCode;
                Assert.AreEqual(WSAEADDRNOTAVAIL, err);
            }
        }

        [Test]
        public void BadUriBadHostFormat_NonThrowingType()
        {
            Uri uri = new Uri("obex://0000000000000000000000000/foo.txt");
            ObexWebRequest req = CreateObexWebRequestOfClassThatDoesNotThrow(uri);
            ObexWebResponse rsp = (ObexWebResponse)req.GetResponse();
            Assert.AreEqual(ObexStatusCode.BadRequest, rsp.StatusCode);
        }

    }//class


    class NewWholeProcessTests_Data
    {
        //--------
        public static readonly byte[] SimplePut1_Data ={ (byte)'a', (byte)'b', (byte)'c', (byte)'d' };
        public static readonly byte[] SimplePut1_Responses ={
            // Connect response
            0xA0, 0,7, 0x10, 0x00, 0x08, 0x00, // MTU=0x800=2048
            // Subsequent response(s)
            0x90, 0,3,
            0xA0, 0,3,
            //
            0xA0, 0,3,
        };
        public static readonly byte[] SimplePut1_ExpectedRequests ={
            //Connect
            0x80, 0x00, 0x07, 0x10, 0x00, 0x20, 0x00,
            //Put
            0x02, 0x00, 0x1D, 0x01, 0x00, 0x15, 0x00, 0x61, 0x00, 0x61, 0x00, 0x61, 0x00, 0x61, 0x00, 0x2E,
                0x00, 0x74, 0x00, 0x78, 0x00, 0x74, 0x00, 0x00, 0xC3, 0x00, 0x00, 0x00, 0x04, 
            //Put
            0x82, 0x00, 0x0A, 0x49, 0x00, 0x07, 0x61, 0x62, 0x63, 0x64,
            //Disconnect
            0x81, 0x00, 0x03
        };

        public static readonly byte[] SimplePut1SimpleNonAsciiFilename_ExpectedRequests ={
            //Connect
            0x80, 0x00, 0x07, 0x10, 0x00, 0x20, 0x00,
            //Put
            0x02, 0x00, 0x23, 
                0x01, 0x00, 0x1b, 
                    // "aáa†a%a.txt"
                    0x00, 0x61, 0x00, 0xE1, 0x00, 0x61, 0x20, 0x21, 0x00, 0x61, 0x00, 0x25, 0x00, 0x61, 
                    0x00, 0x2E,
                    0x00, 0x74, 0x00, 0x78, 0x00, 0x74, 0x00, 0x00, 
                0xC3, 0x00, 0x00, 0x00, 0x04, 
            //Put
            0x82, 0x00, 0x0A, 0x49, 0x00, 0x07, 0x61, 0x62, 0x63, 0x64,
            //Disconnect
            0x81, 0x00, 0x03
        };

        public static readonly byte[] SimplePut1UnicodeWithSurrogatePair_ExpectedRequests ={
            //Connect
            0x80, 0x00, 0x07, 0x10, 0x00, 0x20, 0x00,
            //Put
            0x02, 0, 33, 
                0x01, 0, 25, 
                    0x00, 0x61, 0x00, 0x61, 0xD8, 0x08, 0xDC, 0x04, 0x00, 0x61, 0x00, 0x61, 
                    0x00, 0x2E, 0x00, 0x74, 0x00, 0x78, 0x00, 0x74, 0x00, 0x00, 
                0xC3, 0x00, 0x00, 0x00, 0x04, 
            //Put
            0x82, 0x00, 0x0A, 0x49, 0x00, 0x07, 0x61, 0x62, 0x63, 0x64,
            //Disconnect
            0x81, 0x00, 0x03
        };

        public static readonly byte[] SimplePut1UnicodeChinese_ExpectedRequests ={
            //Connect
            0x80, 0x00, 0x07, 0x10, 0x00, 0x20, 0x00,
            //Put
            0x02, 0x00, 0x1D, 
                0x01, 0x00, 0x15, 
                    0x7A, 0x7A, 0x76, 0x7D, 0x65, 0x87, 0x4E, 0xF6, 
                    0x00, 0x2E, 0x00, 0x64, 0x00, 0x6F, 0x00, 0x63, 0x00, 0x00, 
                0xC3, 0x00, 0x00, 0x00, 0x04, 
            //Put
            0x82, 0x00, 0x0A, 0x49, 0x00, 0x07, 0x61, 0x62, 0x63, 0x64,
            //Disconnect
            0x81, 0x00, 0x03
        };



        public static readonly byte[] SimplePut1_PeerMtuEndsNonZero_Responses ={
            // Connect response
            0xA0, 0,7, 0x10, 0x00, 0x07, 0xFF, // MTU=0x7FF=2047
            // Subsequent response(s)
            0x90, 0,3,
            0xA0, 0,3,
            //
            0xA0, 0,3,
        };

        public static readonly byte[] SimplePut2HugePeerMruAndBigFile_Data = new byte[70000];
        public static readonly byte[] SimplePut2HugePeerMruAndBigFile_Responses ={
            // Connect response
            0xA0, 0,7, 0x10, 0x00, 0xFF, 0xFF, // MTU=0xFFFF=65535
            // Subsequent response(s)
            0x90, 0,3,
            0x90, 0,3,
            0xA0, 0,3,
            //
            0xA0, 0,3,
        };

    }//class


    public abstract class NewWholeProcessTestsInfrastructure
    {
        public virtual Uri CreateObexUriForStreamTest(String filename)
        {
            return new Uri("obex:" + filename);
        }

        //----
        public ObexWebRequest CreateObexWebRequestWithGivenConnectionStream(Stream peer, String filename)
        {
            return new ObexWebRequest(CreateObexUriForStreamTest(filename), peer);
        }

        //----
        MemoryStream InternalDoTest(String filename, byte[] data, Byte[] CannedResponses, bool restrictReadsToSingleBytes)
        {
            MemoryStream ourRequests = new MemoryStream();
            Stream peerResponses = new MemoryStream(CannedResponses, false);
            if (restrictReadsToSingleBytes) {
                peerResponses = new ByteByByteReadStream(peerResponses);
            }
            TwoWayStream peer = new TwoWayStream(peerResponses, ourRequests);
            //
            ObexWebRequest req = CreateObexWebRequestWithGivenConnectionStream(peer, filename);
            //
            Stream put = req.GetRequestStream();
            put.Write(data, 0, data.Length);
            req.ContentLength = data.Length;
            //
            ObexWebResponse rsp = (ObexWebResponse)req.GetResponse();
            //
            return ourRequests;
        }

        internal void DoTest(String filename, byte[] data, Byte[] CannedResponses, Byte[] ExpectedRequests, bool restrictReadsToSingleBytes)
        {
            MemoryStream ourRequests = InternalDoTest(filename, data, CannedResponses, restrictReadsToSingleBytes);
            //
            //TODO Assert.AreEqual.... for InTheHand.Net.Tests.ObexRequest.NewWholeProcessTests.DoTest
            Assert.AreEqual(ExpectedRequests, ourRequests.ToArray());
        }

        internal void DoTest(String filename, byte[] data, Byte[] CannedResponses, bool restrictReadsToSingleBytes)
        {
            /*MemoryStream ourRequests =*/
            InternalDoTest(filename, data, CannedResponses, restrictReadsToSingleBytes);
        }

    }//class


    [TestFixture]
    public class NewWholeProcessTests : NewWholeProcessTestsInfrastructure
    {

        [Test]
        public void SimplePut1()
        {
            DoTest("aaaa.txt", NewWholeProcessTests_Data.SimplePut1_Data, NewWholeProcessTests_Data.SimplePut1_Responses, NewWholeProcessTests_Data.SimplePut1_ExpectedRequests, false);
        }

        [Test]
        public void SimplePut1_PeerMtuEndsNonZero()
        {
            DoTest("aaaa.txt", NewWholeProcessTests_Data.SimplePut1_Data, NewWholeProcessTests_Data.SimplePut1_PeerMtuEndsNonZero_Responses, NewWholeProcessTests_Data.SimplePut1_ExpectedRequests, false);
        }

        [Test]
        public void SimplePut2HugePeerMruAndBigFile()
        {
            DoTest("aaaa.txt", NewWholeProcessTests_Data.SimplePut2HugePeerMruAndBigFile_Data, NewWholeProcessTests_Data.SimplePut2HugePeerMruAndBigFile_Responses, /*SimplePut1_ExpectedRequests,*/ false);
        }

        //--------------------------------------------------------------
        [Test]
        [Explicit]
        public void SimplePut1_PeerRespondsInSingleByteChunks()
        {
            DoTest("aaaa.txt", NewWholeProcessTests_Data.SimplePut1_Data, NewWholeProcessTests_Data.SimplePut1_Responses, NewWholeProcessTests_Data.SimplePut1_ExpectedRequests, true);
        }

    }//class

    [TestFixture]
    public class NewWholeProcessTestsUriPathEncoding : NewWholeProcessTestsInfrastructure
    {
        [Test]
        public void SimplePut1()
        {
            DoTest("aaaa.txt", NewWholeProcessTests_Data.SimplePut1_Data, NewWholeProcessTests_Data.SimplePut1_Responses, NewWholeProcessTests_Data.SimplePut1_ExpectedRequests, false);
        }

        [Test]
        public void SimplePut1WithSlash()
        {
            DoTest("/aaaa.txt", NewWholeProcessTests_Data.SimplePut1_Data, NewWholeProcessTests_Data.SimplePut1_Responses, NewWholeProcessTests_Data.SimplePut1_ExpectedRequests, false);
        }

        [Test]
        public void SimplePut1SimpleNonAsciiUnicodeFilename()
        {
            DoTest("aáa‡a%a.txt", NewWholeProcessTests_Data.SimplePut1_Data, NewWholeProcessTests_Data.SimplePut1_Responses, NewWholeProcessTests_Data.SimplePut1SimpleNonAsciiFilename_ExpectedRequests, false);
        }

        [Test]
        public void SimplePut1UnicodeWithSurrogatePair()
        {
            DoTest("aa\U00012004aa.txt", NewWholeProcessTests_Data.SimplePut1_Data, NewWholeProcessTests_Data.SimplePut1_Responses, NewWholeProcessTests_Data.SimplePut1UnicodeWithSurrogatePair_ExpectedRequests, false);
        }

        [Test]
        public void SimplePut1UnicodeChinese()
        {
            DoTest("空白文件.doc", NewWholeProcessTests_Data.SimplePut1_Data, NewWholeProcessTests_Data.SimplePut1_Responses, NewWholeProcessTests_Data.SimplePut1UnicodeChinese_ExpectedRequests, false);
        }
    }

    [TestFixture]
    public class NewWholeProcessTestsUriPathEncoding_UserDontEscape : NewWholeProcessTestsUriPathEncoding
    {
        public override Uri CreateObexUriForStreamTest(string filename)
        {
#if FX1_1
/*
#endif
#pragma warning disable 618
#if FX1_1
*/
#endif
            return new Uri("obex:" + filename, true);
#if FX1_1
/*
#endif
#pragma warning restore 618
#if FX1_1
*/
#endif
        }
    }


    public class ByteByByteReadStream : ForV1CloseDisposeLikeV2Stream
    {
        Stream m_readStrm;

        protected override void Dispose(bool disposing)
        {
            try {
                m_readStrm.Close();
            } finally {
                base.Dispose(disposing);
            }
        }


        public ByteByByteReadStream(Stream readStrm)
        {
            m_readStrm = readStrm;
        }



        public override bool CanRead { get { return m_readStrm.CanRead; } }

        public override bool CanWrite { get { throw new Exception("The method or operation is not implemented."); /*or false*/} }

        public override bool CanSeek
        {
            get { throw new Exception("The method or operation is not implemented."); }
        }

        public override void Flush()
        {
            throw new Exception("The method or operation is not implemented.");
        }

        public override long Length
        {
            get { throw new Exception("The method or operation is not implemented."); }
        }

        public override long Position
        {
            get { throw new Exception("The method or operation is not implemented."); }
            set { throw new Exception("The method or operation is not implemented."); }
        }

        public override int Read(byte[] buffer, int offset, int count)
        {
            return m_readStrm.Read(buffer, offset, Math.Min(count, 1));
        }

        public override long Seek(long offset, SeekOrigin origin)
        {
            throw new Exception("The method or operation is not implemented.");
        }

        public override void SetLength(long value)
        {
            throw new Exception("The method or operation is not implemented.");
        }

        public override void Write(byte[] buffer, int offset, int count)
        {
            throw new Exception("The method or operation is not implemented.");
        }
    }//class


    public class TwoWayStream : ForV1CloseDisposeLikeV2Stream
    {
        Stream m_readStrm;
        Stream m_writeStrm;

        protected override void Dispose(bool disposing)
        {
            try {
                m_readStrm.Close();
            } finally {
                try {
                    m_writeStrm.Close();
                } finally {
                    base.Dispose(disposing);
                }
            }
        }


        public TwoWayStream(Stream readStrm, Stream writeStrm)
        {
            m_readStrm = readStrm;
            m_writeStrm = writeStrm;
        }



        public override bool CanRead { get { return m_readStrm.CanRead; } }

        public override bool CanWrite { get { return m_writeStrm.CanWrite; } }

        public override bool CanSeek
        {
            get { throw new Exception("The method or operation is not implemented."); }
        }

        public override void Flush()
        {
            throw new Exception("The method or operation is not implemented.");
        }

        public override long Length
        {
            get { throw new Exception("The method or operation is not implemented."); }
        }

        public override long Position
        {
            get
            {
                throw new Exception("The method or operation is not implemented.");
            }
            set
            {
                throw new Exception("The method or operation is not implemented.");
            }
        }

        public override int Read(byte[] buffer, int offset, int count)
        {
            return m_readStrm.Read(buffer, offset, count);
        }

        public override long Seek(long offset, SeekOrigin origin)
        {
            throw new Exception("The method or operation is not implemented.");
        }

        public override void SetLength(long value)
        {
            throw new Exception("The method or operation is not implemented.");
        }

        public override void Write(byte[] buffer, int offset, int count)
        {
            m_writeStrm.Write(buffer, offset, count);
        }
    }//class


    /// <exclude/>
    /// <summary>
    /// An internal abstract <see cref="T:System.IO.Stream"/> used to implement some of the 
    /// Close/Dispose functionality from FXv2 when compiling the library for FXv1.1.
    /// </summary>
    public abstract class ForV1CloseDisposeLikeV2Stream : Stream
    {
#if FX1_1
        /* The sequence of related calls supplied by Stream in V2 is a follows.
         * There is no such sequence in V1 so we supply it in the 
         * ForV1CloseDisposeLikeV2Stream class.
         * 
         * public override void Close()
         *   In base (Stream) calls Dispose(true);
         * public void Dispose()
         *   In base (Stream) calls Close();
         * protected override void Dispose(bool disposing)
         *   In base (AbortableStream) calls CloseCore(true);
         *   and then base.Dispose(disposing);
         */

        public /*virtual*/override void Close()
        {
            this.Dispose(true);
            GC.SuppressFinalize(this);
        }

        public void Dispose()
        {
            this.Close();
        }

        protected virtual void Dispose(bool disposing)
        { }
#endif
    }//class

}
